<?php
$parentCaption = 'Merchants';
$this->pageTitle = $parentCaption;

if (empty($model->id)) {
	$caption = 'Create new merchant';
	$this->breadcrumbs = array(
		$parentCaption => array('index'),
		$caption,
	);
} else {
	$caption = 'Edit';
	$this->breadcrumbs = array(
		$parentCaption => array('index'),
		$model->name => array('view', 'id'=>$model->id),
		$caption,
	);
}

//make categories for merchants
$categories = MerchantObject::Categories();

$category_key = empty($model->category_key) ? 'others' : $model->category_key;

$edit_btn = BUtils::T('edit_btn');
$delete_btn = BUtils::T('delete_btn');
$add_hours_btn = BUtils::T('add_hours_btn');

//set full address
$full_address = '';
if (!empty($model->address)) $full_address = $model->address;
//set lanLng = [];
$full_lanlng = '';
if (!empty($model->latitude) and !empty($model->longitude)) {
	$full_lanlng = "[{$model->latitude}, {$model->longitude}]";
}
//TODO: city and country
if (empty($model->country_code)) $model->country_code = 'FI';
if (empty($model->city)) $model->city = 'Helsinki';

//get url_logo
$url_logo = BUtils::GetPictureUrl($model->url_logo);


//set open hours
$hours_list_op = $hours_list = '';
//define array
$aWeekDays = BUtils::WeekDayKeys(7, true);
$a24Hours = BUtils::AllHour24();
$hours_list = MerchantObject::HtmlBusinessHours($aHours, $aWeekDays, $a24Hours);
if (!empty($aHours)) {
	//set open hours edit style
	foreach ($aHours as $v) {
		$sWeekday = $aWeekDays[$v['week_no']];
		$sHours = $a24Hours[$v['open_hour']] . ' - ' . $a24Hours[$v['close_hour']];
		$hidValue = $v['week_no'] . ',' . $v['open_hour'] . ',' . $v['close_hour'];
		$hours_list_op .= '<div class="item">
<span class="weekday">'.$sWeekday.'</span>
<span class="hours">'.$sHours.'</span>
<a href="javascript:;" class="remove-hours">'.$delete_btn.'</a>
<input type="hidden" value="'.$hidValue.'" name="business_hours['.$v['week_no'].']" />
</div>';
	}
}
?>
<div class="page-header position-relative">
	<h1>
<?php
if (empty($model->id)) {
	echo $caption;
} else {
	echo $model->name;
?>
		<small>
			<i class="icon-double-angle-right"></i>
			<?php echo $caption; ?>
		</small>
<?php } ?>
	</h1>
</div><!--/.page-header-->

<div class="row-fluid">
	<div class="space-6"></div>
	
	<div class="row-fluid">
		<div class="span12">
			<div class="widget-box transparent">
				<div class="widget-header">
					<h4 class="lighter">
						<i class="icon-edit blue"></i> Business Information
					</h4>
				</div>
				<div class="widget-body">
					<div class="widget-main">
<div class="biz-form">
<?php $form = $this->beginWidget('CActiveForm', array(
	'id'=>'merchant-form',
	//'enableAjaxValidation'=>true,
	'enableClientValidation'=>true,
	'clientOptions'=>array(
		'validateOnSubmit'=>true,
	),
)); ?>
<div class="fieldswrap">
<div class="fields">
	<div class="control-group clearfix">
		<div class="lbl"><?php echo $form->labelEx($model,'name'); ?></div>
		<div class="controls">
			<?php echo $form->textField($model,'name', array('class'=>'span10')); ?>
			<?php echo $form->error($model,'name'); ?>
		</div>
	</div>
	<div class="control-group clearfix">
		<div class="lbl"><?php echo $form->labelEx($model,'category_key'); ?></div>
		<div class="controls">
			<?php echo $form->dropDownList($model, 'category_key', $categories, array('empty'=>'')); ?>
			<?php echo $form->error($model,'category_key'); ?>
		</div>
		<div class="help-block"><?php echo BUtils::T('category_business_eg'); ?></div>
	</div>
	<div class="control-group clearfix row-fluid">
		<div class="lbl"><label><?php echo BUtils::T('company_logo_lbl'); ?></label></div>
		<div class="pull-left" style="margin-right:20px;">
			<img class="img-polaroid" id="img_logo" src="<?php echo $url_logo; ?>" style="width:160px;" alg="" />
		</div>
		<div class="pull-left">
<?php $this->widget('ext.EAjaxUpload.EAjaxUpload', array(
	'id' => 'uploadFile',
	'config' => array(
		'buttonName' => BUtils::T('upload_new_picture_eg'),
		'action' => Yii::app()->createUrl('/tools/merchant/uploadLogo', array('id'=>$model->id)),
		'allowedExtensions'=>array("jpg","jpeg","gif","png"),
		'sizeLimit'=>1*1024*1024,
		'onComplete' => "js:function(id, fileName, responseJSON){ handleUploaded(responseJSON); }",
	),
)); ?>
			<div class="help-block">Please first save this merchant profile, then upload logo!.</div>
		</div>
	</div>
</div>
<div class="fields">
	<div class="control-group clearfix">
		<div class="lbl" id="company_address_lbl">
			<label for="MerchantForm_address"><?php echo BUtils::T('location_lbl') ?></label>
		</div>
		<div id="geo-info">
<fieldset class="geo-info" style="display:none;">
	<h3>Address-Details</h3>
	<label>Latitude</label>
	<input name="lat" type="text" value="">
	<label>Longitude</label>
	<input name="lng" type="text" value="">
	<label>Formatted Address</label>
	<input name="formatted_address" type="text" value="">
	<label>Route</label>
	<input name="route" type="text" value="">
	<label>Street Number</label>
	<input name="street_number" type="text" value="">
	<label>Postal Code</label>
	<input name="postal_code" type="text" value="">
	<label>Locality</label>
	<input name="locality" type="text" value="">
	<label>Country Code</label>
	<input name="country_short" type="text" value="">
</fieldset>
<style>
.map_canvas {width: 100%; height: 240px; margin-top:10px;}
.map_canvas:after{content: "Type in an address in the input above."; padding-top: 100px; display: block; text-align: center; font-size: 2em; color: #999;}
</style>
<?php
echo $form->hiddenField($model,'latitude');
echo $form->hiddenField($model,'longitude');
?>
		</div>
		<div class="controls clearfix">
			<?php echo $form->textField($model,'address', array('class'=>'span10', 'style'=>'margin-bottom:0;')); ?>
			<div class="clearfix"></div>
			<span class="tiny">
				<?php echo $form->labelEx($model,'address'); ?>
			</span>
		</div>
		<div class="space clearfix"></div>
		<div class="controls clearfix">
			<span class="tiny">
				<?php echo $form->textField($model,'postcode', array('maxlength'=>8, 'class'=>'input-small')); ?>
				<?php echo $form->labelEx($model,'postcode'); ?>
			</span>
			<span class="tiny">
				<?php echo $form->textField($model,'city', array('class'=>'')); ?>
				<?php echo $form->labelEx($model,'city'); ?>
			</span>
			<span class="tiny" style="display:none;">
				<?php echo $form->textField($model,'country_code', array('readonly'=>'readonly', 'class'=>'input-small')); ?>
				<?php echo $form->labelEx($model,'country_code'); ?>
			</span>
		</div>
		<div class="controls clearfix">
			<div class="space clearfix"></div>
			<span class="tiny" id="biz-area-section"></span>
			<div class="clearfix"></div>
			<div class="map_canvas"></div>
		</div>
		<div class="help-block">
			<?php echo $form->error($model,'address'); ?>
			<?php echo $form->error($model,'postcode'); ?>
			<?php echo $form->error($model,'city'); ?>
			<?php echo $form->error($model,'country_code'); ?>
		</div>
	</div>
</div>
<div class="fields">
	<div class="control-group clearfix">
		<div class="lbl" id="company_phone_lbl"><?php echo $form->labelEx($model,'phone'); ?></div>
		<div class="controls">
			<div class="input-prepend">
				<span class="add-on"><i class="icon-phone"></i></span>
				<?php echo $form->textField($model,'phone', array('class'=>'input-mask-phone')); ?>
			</div>
			<?php echo $form->error($model,'phone'); ?>
		</div>
		<div class="spc"></div>
	</div>
	<div class="control-group clearfix">
		<div class="lbl" id="open_hours_lbl"><?php echo $form->labelEx($model,'opening'); ?></div>
		<div class="ipt" class="hours-select">
			<div id="added-hours" class="added-hours"><?php echo $hours_list_op ?></div>
			<div class="clearfix"></div>
			<span class="tiny">
				<?php echo CHtml::dropDownList('weekday', 7, $aWeekDays, array('class'=>'weekday-op')); ?>
				<?php echo CHtml::dropDownList('hours-open', 9, $a24Hours, array('class'=>'hours-open-op')); ?>
				<?php echo CHtml::dropDownList('hours-close', 17, $a24Hours, array('class'=>'hours-close-op')); ?>
				<button class="button button-compliment button-thin add-hours" value="submit" type="button"><?php echo $add_hours_btn; ?></button>
			</span>
			<div class="clearfix"></div>
		</div>
		<div class="eg"><?php //echo BUtils::T('opening_hours_eg'); ?></div>
		<div class="spc"></div>
	</div>
</div>
<div class="fields">
	<div class="control-group clearfix">
		<div class="lbl"><?php echo $form->labelEx($model,'url_site'); ?></div>
		<div class="controls">
			<div class="input-prepend">
				<span class="add-on"><i class="icon-external-link"></i></span>
				<?php echo $form->textField($model,'url_site', array('class'=>'input-xlarge website-link')); ?>
			</div>
		</div>
	</div>
	<div class="control-group clearfix">
		<div class="lbl"><?php echo $form->labelEx($model,'url_facebook_page'); ?></div>
		<div class="controls">
			<div class="input-prepend">
				<span class="add-on"><i class="icon-facebook-sign"></i></span>
				<?php echo $form->textField($model,'url_facebook_page', array('class'=>'input-xlarge facebook-link')); ?>
			</div>
		</div>
	</div>
	<div class="control-group clearfix">
		<div class="lbl" id="company_brief_lbl"><?php echo $form->labelEx($model,'brief'); ?></div>
		<div class="controls"><?php echo $form->textArea($model,'brief', array('class'=>'autosize-transition span12')); ?></div>
	</div>
</div><!-- end of .fields -->
</div><!-- end of .fieldswrap -->

	<div class="margin actions clearfix">
		<?php echo CHtml::ajaxSubmitButton('Update profile', Yii::app()->createUrl('/tools/merchant/form', array('id'=>$model->id)), array(
			'dataType' => 'json',
			'beforeSend' => 'js:function(){beforeSubmit("#profile-button");}',
			'error' => 'js:function(){errorSubmit("#profile-button");}',
			'success' => 'js:function(data){afterSubmit(data, "#profile-button");}',
		), array('class' => 'btn btn-large btn-info', 'id'=>'profile-button')); ?>
		<?php echo CHtml::button(BUtils::T('back_btn'), array('class'=>'btn btn-large btn-link', 'onclick'=>'history.go(-1);')); ?>
	</div>

<?php $this->endWidget(); ?>
			
</div><!-- end of <div class="biz-form"> -->
					</div><!--/widget-main-->
				</div>
			</div>
		</div><!-- span12 -->
	</div>
</div>
<script type="text/javascript">
var g_address = '<?php echo $model->address; ?>';
var g_initialized = 0;
$(function() {
	$('textarea[class*=autosize]').autosize({append: "\n"});
	
	//add hours
	$('.add-hours').click(function() {
		var weekday_op = $('.weekday-op option:selected');
		var weekday_next_op = weekday_op.next();
		var open_op = $('.hours-open-op option:selected');
		var close_op = $('.hours-close-op option:selected');
		var strHours = open_op.text() + ' - ' + close_op.text();
		var strValue = weekday_op.val() + ',' + open_op.val() + ',' + close_op.val();
		$('#added-hours').append('<div class="item">'
			+'<span class="weekday">'+weekday_op.text()+'</span> '
			+'<span class="hours">' + strHours + '</span> '
			+'<a href="javascript:;" class="remove-hours"><?php echo BUtils::T('delete_btn') ?></a>'
			+'<input type="hidden" value="' + strValue + '" name="business_hours['+weekday_op.val()+']" />'
			+'</div>');
		$('.remove-hours').unbind('click').bind('click', function(){
			$(this).parent().remove();
		});
		//remove all, then select
		$('.weekday-op > option').attr('selected', false);
		weekday_next_op.attr('selected', true);
	});
	$('.remove-hours').unbind('click').bind('click', function(){
		$(this).parent().remove();
	});
	
	//map marker
	var imageIcon = new google.maps.MarkerImage('<?php echo Yii::app()->baseUrl . "/img/markers/pin_{$category_key}.png"; ?>',
		new google.maps.Size(32, 37), new google.maps.Point(0,0), new google.maps.Point(16,37));
	var imageShadow = new google.maps.MarkerImage('<?php echo Yii::app()->baseUrl; ?>/img/markers/pin_shadow.png',
		new google.maps.Size(51, 37), new google.maps.Point(0,0), new google.maps.Point(16,37));
	$("#MerchantForm_address").geocomplete({
		map: '.map_canvas',  details: '.geo-info',
		<?php if(!empty($full_lanlng)) echo "location: {$full_lanlng},"; ?>
		markerOptions: {
			draggable: true,
			icon: imageIcon,
			shadow: imageShadow
		}
	}).bind("geocode:result", function(event, result){
		setLocationValues(result, false);
	}).bind("geocode:dragged", function(event, latLng){
		$('#MerchantForm_latitude').val(latLng.lat());
		$('#MerchantForm_longitude').val(latLng.lng());
		geocoder = new google.maps.Geocoder();
		geocoder.geocode({'latLng': latLng}, function(results, status) {
			if (status == google.maps.GeocoderStatus.OK) {
				if (results[0]) {
					setLocationValues(results[0], true);
				}
			} else {
				alert("Geocoder failed due to: " + status);
			}
		});
	});
});

function handleUploaded(respJSON) {
	if (respJSON.error) {
		$('.qq-upload-button').html('<span>'+respJSON.error+'</span>');
	} else {
		if (respJSON.url_logo) {
			$('#img_logo').attr('src', respJSON.url_logo);
			$('ul.qq-upload-list').delay(1000).html('');
		}
	}
}

function beforeSubmit(eId) {
	$(eId).attr('disabled', true).addClass('button-disabled');
}
function errorSubmit(eId) {
	alert('System error. Please contact us with business@yamii.fi.');
	$(eId).attr('disabled', false).removeClass('button-disabled');
}
function afterSubmit(data, eId) {
	$(eId).removeAttr('disabled').removeClass('button-disabled');
	if (data.success) {
		alert(data.success);
		if (null == data.id) {
			location.href = '<?php echo Yii::app()->createUrl('/tools/merchant') ?>';
		} else {
			location.href = '<?php echo Yii::app()->createUrl('/tools/merchant/view/id') ?>/'+data.id;
		}
	} else {
		for (var ele in data) {
			$('#'+ele).focus();
			return;
		}
	}
}

function setLocationValues(loc, update) {
	var lat = loc.geometry.location.lat();
	var lng = loc.geometry.location.lng();
	var locArray = loc.formatted_address.split(', ');
	if (locArray.length > 2) {
		//console.log(locArray);
		var street_number, address, postal_code, city, country, country_code;
		$.map(loc.address_components, function(obj) {
			switch (obj.types[0]) {
				case 'postal_code':
					postal_code = obj.long_name;
					break;
				case 'country':
					country = obj.long_name;
					country_code = obj.short_name;
					break;
				case 'locality':
				case 'administrative_area_level_3':
				case 'administrative_area_level_1':
					if (city == null) city = obj.long_name;
					break;
				case 'route':
					address = obj.long_name;
					break;
				case 'street_number':
					street_number = obj.long_name;
					break;
			}
		});
		if (country_code != null) {
			$('#MerchantForm_latitude').val(lat);
			$('#MerchantForm_longitude').val(lng);
			$("#MerchantForm_postcode").val(postal_code);
			$("#MerchantForm_city").val(city);
			$("#MerchantForm_country_code").val(country_code);
			if (update) {$('#MerchantForm_address').val(locArray[0]);}
			if (g_initialized < 1 && '' != g_address) $('#MerchantForm_address').val(g_address);
			g_initialized ++;
			//add business ares section
			$.get('<?php echo Yii::app()->createUrl('/tools/merchant/getNeighborhoods') ?>', {city_key: city, neighborhoods: <?php echo json_encode(explode(',', $model->biz_area)); ?>}, function(response) {
				$('#biz-area-section').html(response);
				$(".chzn-select").chosen({max_selected_options:3, width:'360px;'});
			});
		}
	}
}
</script>
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?sensor=false&libraries=places&language=fi_fi"></script>
<script type="text/javascript" src="<?php echo Yii::app()->baseUrl; ?>/js/labs/jquery.geocomplete.min.js"></script>